package com.example.upload.controller;

import com.example.upload.utils.VideoToAudio;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * FileUploadController
 *
 * @author ChenJiaGeng
 * @date 2024/10/17 11:41
 * @since 1.0.0
 */
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @PostMapping("/video")
    public ResponseEntity<Map<String, Object>> uploadVideo(@RequestParam("file") MultipartFile file) {
        try {
            // 1. 保存视频文件
            String videoPath = saveVideoFile(file);

            // 2. 提取音频
            String audioFilePath = "D:/000-total_folder/301-Files/audio";
            String audioPath = VideoToAudio.singleTransform(videoPath, audioFilePath);

            // 3. 返回音频文件路径或其他相关信息
            Path path = Paths.get(audioPath);
            Resource resource = new UrlResource(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                String tempPath = "http://localhost:12500/upload/audio?filename=%s";
                String format = String.format(tempPath, audioPath);
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("audioUrl", format);
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private String saveVideoFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = "D:/000-total_folder/301-Files/video/" + fileName;
        File dest = new File(filePath);
        file.transferTo(dest);
        return filePath;
    }

    @GetMapping("/audio")
    public ResponseEntity<Resource> getAudio(@RequestParam String filename) throws MalformedURLException {
        Path path = Paths.get(filename);
        Resource resource = new UrlResource(path.toUri());

        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    private static final String FILE_DIRECTORY = "D:/000-total_folder/301-Files/audio/"; // 文件存放路径

    @GetMapping("/files/{filename}")
    public ResponseEntity<FileSystemResource> getFile(@PathVariable String filename) {
        File file = new File(FILE_DIRECTORY + filename);
        if (file.exists()) {
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"") // 提示下载
                    .body(new FileSystemResource(file));
        } else {
            return ResponseEntity.notFound().build(); // 文件不存在
        }
    }

}